const path = require("path");
const LibTuniuWrapper = require("lib-tuniu/lib/v0.0.1").Wrapper;



const Toolbox = require("./Toolbox");
const QiniuUniversally = require("upload-qiniu-universally/lib").QiniuUniversally
const qiniu_uni = new QiniuUniversally;





/**
 * @returns {String}
 * @param {String} full_path 
 * @param {Number} part_index 
 * @param {Number} part_counts 
 */
function TARED_NAMING_FUNCRTION(full_path, part_counts, part_index) {
  if (part_counts == 1) {
    return path.basename(full_path);
  } else {
    let max_length = String(part_counts).length;
    if (max_length < 3) max_length = 3;
    let str_index = String(part_index);
    while (str_index.length < max_length) {
      str_index = `0${str_index}`
    }
    return `${path.basename(full_path)}.${str_index}`;
  }
}



/**
 * @returns {Promise<{ok:Boolean,errors:string[],data:{files:[],html:string}}>}
 * @param {String} full_path_to_dir 
 * @param {Boolean} is_tared
 */
function uploadDirToTuniu(full_path_to_dir, is_tared = false) {
  return new Promise(async resolve => {
    let o_getInsTuniu = await LibTuniuWrapper.getValidInstance("fapfap", "taiwan92huji");
    if (!o_getInsTuniu.ok) {
      return resolve({
        ok: false,
        errors: [`fail to get valid instance of "fapfap","taiwan92huji":${o_getIns.msg}`]
      })
    }
    let tuniu = o_getInsTuniu.instance;
    /**@type {string[]} */
    let errors = [];
    let tmp_html = "";
    for (let i = 1; i <= 3; i++) {
      let o_up = await tuniu.safelyUploadDir(full_path_to_dir, 199 * 1024 * 1024, full_path_to_dir,
        is_tared ? TARED_NAMING_FUNCRTION : tuniu.default_part_name_func);
      if (o_up.ok && o_up.files && o_up.files.length >= 1) {
        return resolve({
          ok: true,
          errors: o_up.errors,
          data: {
            files: o_up.files,
            html: o_up.toHTML()
          }
        })
      } else {
        errors.push(`失败于第${i}次上传`);
        errors = errors.concat(o_up.errors);
        tmp_html = o_up.toHTML();
      }
    }
    resolve({
      ok: false,
      errors: errors,
      data: {
        files: [],
        html: tmp_html
      }
    });
  });
}












module.exports = {
  uploadDirToTuniu: uploadDirToTuniu,

  uploadDirToQiniuUniversally:qiniu_uni.do_upload_dir.bind(qiniu_uni)
}